package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartInfoAsyncService;
import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Author: 李旭
 * @Time: 15:44
 * @Description:
 */
@Service
public class CartInfoServiceImpl implements CartInfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private CartInfoAsyncService cartInfoAsyncService;

    //加入购物车
    @Override
    public void addToCart(Long skuId, Integer skuNum, String userId) {

        System.out.println("addToCart:userId:" + userId);//32长度串
        //缓存的Key值
        String cacheKey = RedisConst.USER_KEY_PREFIX + userId +
                RedisConst.USER_CART_KEY_SUFFIX;
        //1:查询当前商品是否在购物车已经存在了
        //Map h(cart:userId) = new HashMap();  一个用户的购物车
        //cart:userId.put(hk(skuId),hv(CartInfo))  //合并数量
        //cart:userId.put(skuId2,CartInfo)
        //cart:userId.put(skuId3,CartInfo)
        //cart:userId.put(skuId4,CartInfo)
        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().
                get(cacheKey, skuId.toString());
        if (null != cartInfo) {
            //2:存在了  追加商品的数量
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            //设置选中
            cartInfo.setIsChecked(1);
            //DB 更新  开启新的线程 在背后默默的去更
            //cartInfoMapper.updateById(cartInfo);//连接  注解的方式开启新的线程
            cartInfoAsyncService.updateAsyncById(cartInfo);
            System.out.println("addToCart:" + Thread.currentThread().getName());
        } else {
            //3:不存在了
            cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            //skuId
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);//从缓存中取出了
            //放入购物车时的价格
            cartInfo.setCartPrice(skuInfo.getPrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setImgUrl(skuInfo.getSkuDefaultImg());
            cartInfo.setSkuName(skuInfo.getSkuName());
            cartInfo.setIsChecked(1);
            //实时价格
            BigDecimal price = productFeignClient.getPrice(skuId);
            cartInfo.setSkuPrice(price);
            //cartInfoMapper.insert(cartInfo);//多线程  备份
            cartInfoAsyncService.insertAsync(cartInfo);
        }
        //添加或修改 更新缓存
        redisTemplate.opsForHash().put(cacheKey, skuId.toString(), cartInfo);
    }
    //去购物车添加成功页面
    @Override
    public CartInfo toCart(Long skuId) {
        //无敌版  麻烦版
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        System.out.println("toCart:userId:" + userId);
        //缓存的Key值
        String cacheKey = RedisConst.USER_KEY_PREFIX + userId +
                RedisConst.USER_CART_KEY_SUFFIX;
        return (CartInfo) redisTemplate.opsForHash().get(cacheKey,skuId.toString());
    }

    //查询购物车集合
    @Override
    public List<CartInfo> cartList(String userId, String userTempId) {

        //1:判断当前用户是否登录
        if(!StringUtils.isEmpty(userId)){
            //登录了
            if(!StringUtils.isEmpty(userTempId)){
                //有临时用户ID  合并（真实+临时）用户的购物车集合
                return mergeCartList(userId,userTempId);
            }else{
                //没有临时用户ID  直接查询真实用户ID的购物车集合
                return getCartListByUserId(userId);
            }
        }else{
            //未登录
            if(!StringUtils.isEmpty(userTempId)){
                //有临时用户ID  直接查询临时用户的购物车集合
                return getCartListByUserId(userTempId);
            }
        }
        //没有临时用户ID 直接返回NULL
        return null;
    }

    // //选中或取消 购物车
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取真实用户ID
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        //缓存的Key值
        String cacheKey = RedisConst.USER_KEY_PREFIX + userId +
                RedisConst.USER_CART_KEY_SUFFIX;
        //1:更新缓存
        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().
                get(cacheKey, skuId.toString());
        if(null != cartInfo){
            //更新选中或取消状态
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(cacheKey,skuId.toString(),cartInfo);
            //2:更新DB
            cartInfoMapper.update(cartInfo,new QueryWrapper<CartInfo>()
              .eq("user_id",userId).eq("sku_id",skuId));
        }
    }
    //商品清单  购物车中选中了商品集合
    @Override
    public List<CartInfo> checkedCartInfoList(String userId) {
        //缓存的Key值
        String cacheKey = RedisConst.USER_KEY_PREFIX + userId +
                RedisConst.USER_CART_KEY_SUFFIX;
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cacheKey);
        //    boolean test(T t);
        return cartInfoList.stream().filter(cartInfo -> (cartInfo.getIsChecked() == 1)
        ).collect(Collectors.toList());
    }

    //合并（真实+临时）用户的购物车集合
    private List<CartInfo> mergeCartList(String userId, String userTempId) {
        //1:根据真实用户ID查询购物车集合
        List<CartInfo> cartListByUserId = getCartListByUserId(userId);
        //2:根据临时用户ID查询购物车集合
        List<CartInfo> cartListByUserTempId = getCartListByUserId(userTempId);
        //3:判断购物车集合是否有值
        if(!CollectionUtils.isEmpty(cartListByUserId)){
            //真实用户ID有购物车集合
            if(!CollectionUtils.isEmpty(cartListByUserTempId)){
                //临时用户ID有购物车集合的  Map <skuId,CartInfo>

                Map<Long, CartInfo> cartInfoMapByUserId = cartListByUserId.stream().collect(
                        Collectors.toMap(CartInfo::getSkuId, cartInfo -> cartInfo));
                //缓存的Key值
                String cacheKeyByUserId = RedisConst.USER_KEY_PREFIX + userId +
                        RedisConst.USER_CART_KEY_SUFFIX;
                String cacheKeyByUserTempId = RedisConst.USER_KEY_PREFIX + userTempId +
                        RedisConst.USER_CART_KEY_SUFFIX;
                //大合并开始
                cartListByUserTempId.forEach(cartInfoByUserTempId -> {
                    CartInfo cartInfoByUserId = cartInfoMapByUserId.
                            get(cartInfoByUserTempId.getSkuId());
                    if(null != cartInfoByUserId){
                        //1:如果出现相同商品数量之和
                        cartInfoByUserId.setSkuNum(
                                cartInfoByUserTempId.getSkuNum() +
                                        cartInfoByUserId.getSkuNum());
                        //选中
                        cartInfoByUserId.setIsChecked(1);
                        //更新DB
                        //1）更新真实用户的购物车数量
                        cartInfoMapper.updateById(cartInfoByUserId);
                        //2)删除 临时用户的数据
                        cartInfoMapper.deleteById(cartInfoByUserTempId.getId());
                        //更新Redis
                        redisTemplate.opsForHash().put(cacheKeyByUserId,
                                cartInfoByUserId.getSkuId().toString(),cartInfoByUserId);
                        redisTemplate.opsForHash().delete(cacheKeyByUserTempId,
                                cartInfoByUserTempId.getSkuId().toString());
                    }else{
                        //2:如果出现不相同的商品直接添加
                        cartInfoMapByUserId.put(cartInfoByUserTempId.getSkuId(),
                                cartInfoByUserTempId);
                        //更新DB
                        //修改用户ID
                        cartInfoByUserTempId.setUserId(userId);
                        cartInfoMapper.updateById(cartInfoByUserTempId);
                        redisTemplate.opsForHash().put(cacheKeyByUserId,
                                cartInfoByUserTempId.getSkuId().toString(),cartInfoByUserTempId);
                        redisTemplate.opsForHash().delete(cacheKeyByUserTempId,
                                cartInfoByUserTempId.getSkuId().toString());
                    }
                });
                //合并后购物车集合
                return  new ArrayList<>(cartInfoMapByUserId.values());
            }else{
               //临时用户ID没有购物车集合的
                return cartListByUserId;
            }
        }else{
            //真实用户ID没有购物车集合  不需要合并
            return cartListByUserTempId;
        }
    }

    //根据用户ID获取购物车集合   用户ID：临时用户ID 还是真实用户ID 都可以
    private List<CartInfo> getCartListByUserId(String userId) {
        //缓存的Key值
        String cacheKey = RedisConst.USER_KEY_PREFIX + userId +
                RedisConst.USER_CART_KEY_SUFFIX;
        // Map h
        // 获取Map的所有Value值集合  HashMap是无序的
        // h.values();
        Date date = new Date();
        long time = date.getTime();
        //排序
        List<CartInfo> values = redisTemplate.opsForHash().values(cacheKey);
        //   int compare(T o1, T o2);
        // 10
        return values.stream().sorted((cartInfo1,cartInfo2) -> {
            //return cartInfo1.getSkuNum() - cartInfo2.getSkuNum();//降   -1 0  1
            return cartInfo2.getSkuNum() - cartInfo1.getSkuNum();//升
        }).collect(Collectors.toList());


    }
}
